<?php

class EmployeesController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	
        public function actionUploadImage($empno){
            
                $model = Employees::model()->findByPk($empno);
                $model->handleImageSaving();
                if($model->save()){
                    $this->showAjaxMessage(getImageBySize($model->image,150,150),true);
                }else{
                    $this->showAjaxMessage('Upload faield',false);
                }
            
            
          
        }
	

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Employees;
                $model->status=1;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
                $model->hrrate=NULL;
		if(isset($_POST['Employees']))
		{
			$model->attributes=$_POST['Employees'];
                        
                        
			if($model->save())
				$this->redirect(array('update','empno'=>$model->empno));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($empno)
	{
		$model=$this->loadModel($empno);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
                $model->hrrate=NULL;
		if(isset($_POST['Employees']))
		{
                    
			$model->attributes=$_POST['Employees'];
            $user=Users::model()->findByPk(Yii::app()->user->id);
            /* @var $user Users */
            if($user!=NULL 
                && $user->checkPermission(Users::PRIVILEGE_EMPLOYEE_ADMIN) 
                && $user->checkPermission(Users::PRIVILEGE_SHOW_PAYRATE)){
                
                $model->hrrate=$_POST['Employees']['hrrate'];
            }else{
                $model->hrrate=NULL;
            }
			if($model->save()){
                if(Yii::app()->request->isAjaxRequest){
                    $this->showAjaxMessage('Save successful',true);
                }                
            }else{            
                if(Yii::app()->request->isAjaxRequest){
                    $this->showAjaxMessage($model->errors,false);    
                }
                
            }
				
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
	
            
            $this->loadModel($id)->delete();
            
	
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
	
		$this->render('index',array(
	
		));
	}
        public function actionSchedule($empno){
            $model=$this->loadModel($empno);
            if(isset($_POST['Employees'])){
                $model->attributes=$_POST['Employees'];
                $model->save();
            }
            $this->render('schedule',array(
                'model'=>$model,
            ));
        }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($empno)
	{
		$model=Employees::model()->findByPk($empno);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='employees-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        public function actionList($status=null,$query=null,$page=0,$sort=NULL,$dir=NULL){
            if($page>0)$page--;
            $order=CJSON::decode($sort);
            $crit=new CDbCriteria();
            $crit->addCondition("unassign != 'Y'");
            $crit->compare('status', $status);
            if($query!=null){
                $crit->addCondition('empno like :query or firstname like :query or lastname like :query or title like :query or dept like :query');
                $crit->params['query']="%$query%";
            }
            if($sort!=null){
                $crit->order=$order[0]['property'].' '.$order[0]['direction'];
            }
            $data=new CActiveDataProvider('Employees',array(                                
                'criteria'=>$crit,
                'pagination'=>array(
                    'pageSize'=>20,
                    'currentPage'=>$page,
                )
            ));
            
            if($data!=NULL && count($data->getData())>0){
                $rs=array();
                $rs['totalCount']=$data->getTotalItemCount();
                foreach($data->getData() as $i=>$item){
                    $rs['data'][$i]=$item->getAttributes();
                    
                }
                echo json_encode($rs);
            }
            Yii::app()->end();
        }
        public function actionGetSocsecnumber($empno){
            //$users=getUserByPermission(Users::PRIVILEGE_SHOW_SSNUMBER);            
            //TROY- fix bug permission
            $isValid = Users::model()->checkPermission('employees/getsocsecnumber', Yii::app()->user->id);
            //if(in_array(Yii::app()->user->name,$users)){             
            if($isValid){
                $socsec=Yii::app()->db->createCommand('select socsecnum from tbl_employees where empno=:empno')->bindValue('empno',$empno)->queryScalar();
                if(strlen($socsec)==0)
                    echo "Not Found";
                else{
                    $crypt=new cryptastic();
                    echo $crypt->decrypt($socsec,Yii::app()->params['encryptKey']);                
                }
            }else{
                echo 'You do not have enough permission';
            }
        }
        public function actionGetHourRate($empno){
            $user=Users::model()->findByPk(Yii::app()->user->id);
            /* @var $user Users */
            if($user!=NULL 
                && $user->checkPermission(Users::PRIVILEGE_EMPLOYEE_ADMIN) 
                && $user->checkPermission(Users::PRIVILEGE_SHOW_PAYRATE)){
                
                $data=Yii::app()->db->createCommand('select hrrate from tbl_employees where empno=:empno')
                        ->bindValue('empno', $empno)->queryScalar();
                echo $data;
            }
            echo '';
        }
        
    public function actionShiftTime()
    {
      if(isset($_POST)){
          $shift_num = $_POST['shift_num'];
          $shift = '';
          if($shift_num == 1)
          {
              $shift = '08:00:00';
              $shift .= ',';
              $shift .= '17:00:00';
          }
          elseif($shift_num == 2)
          {
              $shift = '09:00:00';
              $shift .= ',';
              $shift .= '18:00:00';
          }

          echo $shift;
      }
    }
    
    public function actionPrintEmployee()
    {
        $crit=new CDbCriteria();
        $crit->addCondition("unassign = '' AND status = 1");
        $crit->order = 'lastname';
        $data=Employees::model()->findAll($crit);
        
        if($data!=NULL && count($data)>0){
            $rs=array();
            foreach($data as $i=>$item){
                $rs[$i]=$item->getAttributes();
            }
        }
        
        $this->renderPartial('print',array(
            'record'=>$rs,
        ));        
    }
}
